package com.djsearch.ui;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import com.djsearch.R;
import com.djsearch.adapter.CityCheckExpListViewAdapter;
import com.djsearch.adapter.SearchWayPopuAdapter;
import com.djsearch.adapter.SortPopuWindowAdapter;
import com.djsearch.bean.GoodsBaseBean;
import com.djsearch.controller.DefaultController;
import com.djsearch.controller.JSONResp;
import com.djsearch.ui.TaoGouActivity.RequestParamStruct;
import com.djsearch.widget.MyDialog;
import com.djsearch.widget.ScrollLayout.OnScrollToScreenListener;
import com.tencent.weibo.api.TAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.net.RequestListener;

import android.R.bool;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @author chenyang2
 * @version 1.0
 *
 */

public abstract class BaseActivity extends Activity{
	public static DefaultController HTTP = DefaultController.getHttpClient();
	public DisplayMetrics displayMetrics;
	private Context mContext;
	private LinearLayout cityWindowLayout,searchWayLayout;
	private LayoutInflater inflater;
	private int width;
	private int height;
	public static int whichScreen = 0;

	private List<String> groupArray = new ArrayList<String>();;// 组列表
	private List<List<String>> childArray = new ArrayList<List<String>>();;// 子列表
	private PopupWindow cityCheckPopupWindow;//身份城市选择窗口
	private View mainCenterLayout;//底部布局，中间布局
	public PopupWindow progressBarPopuWindow;
	private RelativeLayout progressBarLayout;
	private PopupWindow searchWayPopupWindow;
	public  SharedPreferences preferences;
	public ProgressDialog progressDialog;
	
	public List<String> list = new ArrayList<String>(); 
	public List<String> listTag = new ArrayList<String>(); 
	public ListView searchWayListView;//searchWayPopupWindow中的下拉列表
	public List<String> sortList = new ArrayList<String>(); 
	public SortPopuWindowAdapter sortPopuWindowAdapter;
	private RequestDataListner onRequestDataListner = null;
	MyDialog dialog;
	
	public OAuthV2 oAuth;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// 得到屏幕的分辨率
		getDisPlayMetrics();
		initSearchWayLayout();
		mContext = this;
		/**
		 * 建立一个本地文件,用于保存小数据
		 */
		preferences = this.getSharedPreferences("KeySet", 0);
		
		getData();
	}
	
	
	public LinearLayout initCityWindowLayout(){
		inflater = (LayoutInflater) this
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		cityWindowLayout = (LinearLayout) inflater.inflate(
				R.layout.city_popuwindow_item, null);
		final ExpandableListView cityExpListView = (ExpandableListView)cityWindowLayout
		                                .findViewById(R.id.cityExdListView);
		final CityCheckExpListViewAdapter cityCheckExpListViewAdapter = 
			new CityCheckExpListViewAdapter(this, groupArray, childArray);
		/**
		 * 该监听是实现只展开当前点击某一项
		 */
        cityExpListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
			
			@Override
			public void onGroupExpand(int groupPosition) {
				// TODO Auto-generated method stub
				for (int i = 0; i < cityCheckExpListViewAdapter.getGroupCount(); i++) {
					if (groupPosition != i) {
						cityExpListView.collapseGroup(i);
					}
				}
					
			}
		});
//		initDate();
		cityExpListView.setGroupIndicator(null);
		cityExpListView.setAdapter(cityCheckExpListViewAdapter);
		return  cityWindowLayout;
	}

	public LinearLayout initSearchWayLayout() {
		inflater = (LayoutInflater) this
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		searchWayLayout = (LinearLayout) inflater.inflate(
				R.layout.searchway_popuwindow_item, null);
		searchWayListView = (ListView)searchWayLayout
		                                .findViewById(R.id.searchwayListView);
//		searchWayListView.setAdapter(new SearchWayPopuAdapter(this,list, listTag));
		sortPopuWindowAdapter = new SortPopuWindowAdapter(this,sortList);
		searchWayListView.setAdapter(sortPopuWindowAdapter);
		searchWayListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				missSearchPopuWindow();
				onRequestDataListner.requestData(position);
			}
		});
		
		return  searchWayLayout;
	}
	
	
	public LinearLayout initCityLayout(final TextView textView) {
		inflater = (LayoutInflater) this
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		searchWayLayout = (LinearLayout) inflater.inflate(
				R.layout.searchway_popuwindow_item, null);
		searchWayListView = (ListView)searchWayLayout
		                                .findViewById(R.id.searchwayListView);
		searchWayListView.setAdapter(new SearchWayPopuAdapter(this,list, listTag));
//		searchWayListView.setAdapter(sortPopuWindowAdapter);
		searchWayListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
//				missSearchPopuWindow();
				textView.setText(list.get(position));
				if (cityCheckPopupWindow != null && cityCheckPopupWindow.isShowing()) {
					cityCheckPopupWindow.dismiss();
				}
			}
		});
		
		return  searchWayLayout;
	} 
	
	
	
	/**
	 * 初始化"正在刷新"...布局
	 * @return
	 */
	public RelativeLayout initProgressBarLayout() {
		inflater = (LayoutInflater) this
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		progressBarLayout = (RelativeLayout) inflater.inflate(
				R.layout.progressbar_popwindow_layout, null);
		return progressBarLayout;
	}
	/**
	 * 初始化"正在刷新"...窗口
	 */
	private void initProgressBarPopWindow() {
		progressBarPopuWindow = new PopupWindow(initProgressBarLayout(),
				getWidth(), getHeight()/10);
		progressBarPopuWindow.setAnimationStyle(R.style.menuPopupAnimation);
		progressBarPopuWindow.setFocusable(true);
		progressBarPopuWindow.setOutsideTouchable(true);
		
	}
	/**
	 * 显示"正在刷新..."窗口
	 * @param v
	 */
	public void showProgressBarPopWindow(View v){

		if (progressBarPopuWindow == null) {
			initProgressBarPopWindow();
		}
		if (progressBarPopuWindow.isShowing()) {
			progressBarPopuWindow.dismiss();
		} else {
			progressBarPopuWindow.update();
			progressBarPopuWindow.showAtLocation(v, Gravity.BOTTOM ,
					30,0);
//			progressBarPopuWindow.showAtLocation(parent, gravity, x, y);
		}
	
	}
	
	
	/**
	 * 初始化查询方式窗口，比如：按照5000米内查找，或按照分类查找等窗口
	 * 该窗口在团购，淘购等页面出现
	 */
	private void initSearchWayPopupWindow(View view1,int height) {
		searchWayPopupWindow = new PopupWindow(initSearchWayLayout(),
				view1.getWidth(), height);
		searchWayPopupWindow.setAnimationStyle(R.style.SearchWayPopuAnimation);
		searchWayPopupWindow.setFocusable(true);
		searchWayPopupWindow.setBackgroundDrawable(new BitmapDrawable());
	}
	
	/**
	 * 显示"查询方式窗口..."窗口
	 * @param v
	 */
	public void showSearchWayPopupWindow(View v,int height,int fromX){

//		if (searchWayPopupWindow == null) {
			initSearchWayPopupWindow(v,height);
//		}
		if (searchWayPopupWindow.isShowing()) {
			searchWayPopupWindow.dismiss();
		} else {
			searchWayPopupWindow.update();
			searchWayPopupWindow.showAtLocation(v, Gravity.BOTTOM ,
					fromX,10);
		}
	
	}
	
	
	
	public void getDisPlayMetrics(){
		displayMetrics = new DisplayMetrics();
	    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
	    setWidth(displayMetrics.widthPixels);
	    setHeight(displayMetrics.heightPixels);
	}
	//
	private void initPopWindow(TextView textView) {
//		cityCheckPopupWindow = new PopupWindow(initCityWindowLayout(),
//				getWidth()/2, mainCenterLayout.getHeight()+32);
		cityCheckPopupWindow = new PopupWindow(initCityLayout(textView),
				getWidth()/2, mainCenterLayout.getHeight()+32);
		cityCheckPopupWindow.setAnimationStyle(R.style.menuPopupAnimation);

		cityCheckPopupWindow.setFocusable(true);
		cityCheckPopupWindow.setBackgroundDrawable(new BitmapDrawable());
	}
	
	/**
	 * 显示窗口
	 * @param v 在哪个控件旁显示控件
	 */
	
	public void popWindow(View v,TextView textView) {
		if (cityCheckPopupWindow == null) {
			initPopWindow(textView);
		}
		if (cityCheckPopupWindow.isShowing()) {
			cityCheckPopupWindow.dismiss();
		} else {
			cityCheckPopupWindow.update();
			cityCheckPopupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.LEFT,
					0, v.getHeight()-23);
		}
	}
	
	/**
	 * 消失popu
	 * @return
	 */
	public void missSearchPopuWindow() {
		if (searchWayPopupWindow != null &&
				searchWayPopupWindow.isShowing()) {
			searchWayPopupWindow.dismiss();
		}
	}
	
	public int getWidth() {
		return width;
	}
	public void setWidth(int width) {
		this.width = width;
	}
	public int getHeight() {
		return height;
	}
	public void setHeight(int height) {
		this.height = height;
	}
	public RelativeLayout getMainCenterLayout() {
		return (RelativeLayout) mainCenterLayout;
	}
	public void setMainCenterLayout(View mainCenterLayout) {
		this.mainCenterLayout = mainCenterLayout;
	}

	/**
	 * 判断是否登录
	 * @return true表示登录，false 为未登录
	 */
	public boolean isLogin(){
		boolean isLogin = preferences.getBoolean("isLogined",false); 
		return isLogin;
	}
	
	
	/**
	 * 页面跳转方法
	 * @param fromActivity 当前页面
	 * @param toActivity    跳转到页面
	 * @param isEnterOrBack 进入页面还是返回页面 0 表示进入，1表示返回
	 * 
	 */
	public  void startActivity(Context fromActivity ,Class<?> toActivity,int isEnterOrBack){
		Intent intent;
		if (isEnterOrBack == 0) {
			//进入页面
			intent=new Intent(fromActivity, toActivity);
			startActivity(intent);
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		} else {
			((Activity) fromActivity).finish();
			overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
		}
	}
	
	
	/**
	 * 页面跳转方法(该方法可以页面间传递数据，这里用对象的方式传递)
	 * @param fromActivity 当前页面
	 * @param toActivity    跳转到页面
	 * @param isEnterOrBack 进入页面还是返回页面 0 表示进入，1表示返回
	 * @param goodsBaseBean 需要传递的对象  GoodsBaseBean 是所传递对象的父类
	 * 
	 */
	public  void startActivity(Context fromActivity ,Class<?> toActivity,int isEnterOrBack,
			GoodsBaseBean goodsBaseBean){
		Intent intent;
		if (isEnterOrBack == 0) {
			//进入页面
			intent=new Intent(fromActivity, toActivity);
			intent.putExtra("data", goodsBaseBean);
			startActivity(intent);
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		} else {
			((Activity) fromActivity).finish();
			overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
		}
	}
	
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}
	
	public void showDialog(String message) {
		if (progressDialog == null) {
			initDialog();
		}
		progressDialog.setMessage(message);
		if (!progressDialog.isShowing()) {
			progressDialog.show();
		}
	}

	private void initDialog() {
		progressDialog = new ProgressDialog(this);
//		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(true);
		progressDialog.setView(initProgressBarLayout());
	}
	
	public void missDialog(){
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}
	
	/**
	 * 显示进度条
	 * 如请求数据刷新过程中显示
	 */
	public void showProgressBar(View v) {
		showProgressBarPopWindow(v);
	}
	
	/**
	 * 消失进度条
	 * 如数据请求完毕，则消失该进度条
	 */
	public void missProgressBar() {
		if (progressBarPopuWindow != null && progressBarPopuWindow.isShowing()) {
			progressBarPopuWindow.dismiss();
		}
	}
	/**
	 * 界面提示调用方法
	 */
	public void toast(String messageString) {
//		Toast.makeText(this, messageString, "5000").show();
	}
	
	/**
	 * 主线程消息处理功能，主要是数
	 * 据获取时的处理，防止界面卡
	 */
	
	abstract void initHandler();
	/**
	 * 初始化页面
	 */
	abstract void initView() ;
	
	/**
	 * 初始化点击事件
	 */
	abstract void initOnClick();
	/**
	 * 成功请求到数据后去处理
	 */
	abstract void getDataToResolve(JSONResp response);
	
	/**
	 * 写入到文件中(保存小数据)
	 */
	public void writeKeyToFile(int key){
		 SharedPreferences.Editor editor = preferences.edit();
		 editor.putInt("key", key).commit();
	}
	/**
	 * 取出小数据
	 */
	public int readKeyFromFile(){
		int key = preferences.getInt("key", 1);
		return key;
	}
	
	/**
	 * 初始化城市列表数据
	 */
	public void getData() { 
	    String city_name_list[] = this.getResources() 
	            .getStringArray(R.array.city_description_list); 
	    String cityTag[] = { "热门城市", "A", "B", "C", "D", "E", "F", "G", "H", "J", 
	            "K", "L", "M", "N", "Q", "S", "T", "W", "X", "Y", "Z" }; 
	    int listsize[] = { 0, 18, 5, 6, 9, 7, 1, 3, 6, 13, 13, 5, 8, 5, 7, 7, 
	            10, 6, 11, 7, 11, 9 }; 
	    for (int j = 1; j < listsize.length; j++) { 
	        list.add(cityTag[j - 1]); 
	        listTag.add(cityTag[j - 1]); 
	        listsize[j] = listsize[j - 1] + listsize[j]; 
	        for (int i = listsize[j - 1]; i < listsize[j]; i++) { 
	            list.add(city_name_list[i]); 
	        } 
	    } 
	} 
	
	interface RequestDataListner {
		void requestData(int position);
	}
	public void setOnRequestDataListner(RequestDataListner 
			onScrollToScreenListener) {
		this.onRequestDataListner = onScrollToScreenListener;
	}

	public void startAnimation(View editText) {
		Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		editText.startAnimation(shake);
	}
   
	/**
	 * 点击返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(mContext, null, 1);
		}
		return false;
	}
//	/**
//	 * 分享方法
//	 * @param shareContent 分享的商品内容及其链接
//	 * 如：groupBuyGoods.getShopDescripe()+":"+ groupBuyGoods.getShopUrl()
//	 */
//	public void share(String shareContent) {
//		Intent intent=new Intent(Intent.ACTION_SEND);   
//        intent.setType("image/*");   
//        intent.putExtra(Intent.EXTRA_SUBJECT, "Share");   
//        intent.putExtra(Intent.EXTRA_TEXT, shareContent);   
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
//        startActivity(Intent.createChooser(intent, getTitle()));
//	}
	
	/**
	 * 判断网络是否可用̬
	 */
	public boolean isAccessNetwork(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity.getActiveNetworkInfo() != null
				&& connectivity.getActiveNetworkInfo().isAvailable()) {
			return true;
		}
		return false;
	}
	
	/**
	 * 判断是否绑定了新浪微博
	 * @return
	 */
	public boolean isBindSina() {
		String token = preferences.getString("sinaToken", "");
		String expires_in = preferences.getString("sinaexpiresIn", "");
		if (token.equals("") || expires_in.equals("")) {
			return false;
		}
		return true;
 	}
	
	/**
	 * 得到新浪微博的AccessToken
	 * @return
	 */
	public Oauth2AccessToken getAccessToken() {
		String token = preferences.getString("sinaToken", "");
		String expires_in = preferences.getString("sinaexpiresIn", "");
		return new Oauth2AccessToken(token, expires_in);
	}
	/**
	 * 分享内容到新浪微博
	 * @param content
	 */
	public void shareContentToSinaWeibo(String content) {
		StatusesAPI api = new StatusesAPI(getAccessToken());
		api.update(content, "", "", new RequestListener() {
			@Override
			public void onIOException(IOException arg0) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onError(WeiboException arg0) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onComplete(String arg0) {
				// TODO Auto-generated method stub

			}
		} );
	}
	
//	public void shareContentToTecentWeibo(String content) {
//		TAPI tAPI = new TAPI(OAuthConstants.OAUTH_VERSION_2_A);
////		Object token = preferences.getString("tecentToken", "");
//		String clientId = preferences.getString("clientId", "");
//		String clientSecret = preferences.getString("clientSecret", "");
//		String redirectUri = preferences.getString("redirectUri", "");
//		OAuthV2 oAuth = new OAuthV2(clientId, clientSecret, redirectUri);
//		try {
//			tAPI.add(oAuth, "json", content, "127.0.0.1");
//		} catch (Exception e) {
//			// TODO: handle exception
//		} finally {
////			tAPI.shutdownConnection();
//		}
//	}
	
	
}
